package core.reports;

import java.io.IOException;
import java.util.List;
import java.util.ArrayList;

/**
 * This implementation of IReportBuilder saves the table in a data structure.  It is then possible
 * to get the collected data out of this class to run tests on.
 * @author Royce
 *
 */
public class TestBuilder implements IReportBuilder {
	
	/**
	 * A representation of the given data as a data structure that represents a table.
	 */
	private List<List<String>> data;
	
	private int numCols;
	private int curCol;
	private int curRow;
	
	/**
	 * Default no-arg constructor.  This initializes the data structure.
	 */
	private TestBuilder() {
		data = new ArrayList<List<String>>();
		data.add(new ArrayList<String>());
		numCols = -1;
		curCol = 0;
		curRow = 0;
	}
	
	public TestBuilder(String fileName, String title) throws IOException {
		this();
		openFile(fileName, title);
		addParagraph(title, true);
	}
	
	public TestBuilder(String title) throws IOException {
		this();
		addParagraph(title, true);
	}
	
	@Override
	public void openFile(String fileName, String title) throws IOException {
		//ignored by TestBuilder
	}

	@Override
	public void startTable(String title, int cols) throws IOException {
		//ignore the title
		completeRow();
		addParagraph(title, true);
		numCols = cols;
	}

	@Override
	public void addCell(Object o) {
		if(curCol == 0) {
			data.add(new ArrayList<String>());
		}
		
		data.get(curRow).add(o.toString());
		curCol++;
		if (curCol == numCols) {
			data.add(new ArrayList<String>());
			curCol = 0;
			curRow++;
		}

	}

	@Override
	public void completeRow() {
		if(curCol == 0) return;
		
		while(curCol < numCols) {
			data.get(curRow).add("");
			curCol++;
		}
		curCol = 0;

	}

	@Override
	public void print() throws IOException {
		//ignored by TestBuilder

	}
	
	/**
	 * 
	 * @return the collected data so far.
	 */
	public List<List<String>> getData() {
		return data;
	}

	@Override
	public void addParagraph(String s, boolean isSubHeader) throws IOException {
		//TODO: how should this be reflected in the data structure?
		completeRow();
		addCell(s);
		completeRow();	
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		TestBuilder other = (TestBuilder) obj;
		if (data == null) {
			if (other.data != null)
				return false;
		} else if (!data.equals(other.data))
			return false;
		return true;
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((data == null) ? 0 : data.hashCode());
		return result;
	}

}
